<template>
	<view class="track">
		<view class="form">
			<view class="form-group">
				<view 
					class="form-item" 
					v-for="(item, index) in searchData" 
					:key="index">
					<text class="form-item-header">{{ item.label }}：</text>
					<view class="form-item-body" v-if="item.type == 'cal'">
						<picker mode="date" @change="bindDateChange($event, item)">
							<view class="cals">
								<view class="cals-item-content">{{ item.value || '开始时间'}}</view>
								<image class="cals-icon" src="@/static/icon/iv_calendar2.png"></image>
							</view>
						</picker>
					</view>
					<view class="form-item-body" v-else>
						<picker 
							:value="item.index" 
							:range="item.options" 
							range-key="name" 
							@change="bindPickerChange($event, item)">
							<view class="select">
								<view class="selected">
									<text class="selected-con">{{ item.value | getDictLabel(item.options, 'code') || '请选择'}}</text>
								</view>
								<view class="select-icon">
									<uni-icons type="arrowdown" size="22" color="#c4c4c4" />
								</view>
							</view>
						</picker>
					</view>
				</view>
			</view>
		</view>
		<view 
			class="map-wrap" 
			id="amap" 
			:prop="option" 
			:change:prop="amap.updateMap">
		</view>
	</view>
</template>

<script module="amap" lang="renderjs">
	export default {
		data() {
			return {
				map: null,
				pathSimplifierlns: null
			}
		},
		methods: {
			updateCruise(data) {
				let _this = this;
				
				if(this.pathSimplifierIns){
					this.pathSimplifierIns.setData([{
						name: '路线0',
						path: []
					}]);
				}
				
				if(data[0].points.length == 0){
					return ;
				}
				
				AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function(PathSimplifier, $) {
					if (!PathSimplifier.supportCanvas) {
						alert('当前环境不支持 Canvas！');
						return;
					}

					let pathSimplifierIns = new PathSimplifier({
						zIndex: 100,
						map: _this.map, //所属的地图实例
						getPath: function(pathData, pathIndex) {
							return pathData.path;
						}, 
						renderOptions: {
							pathLineStyle: {
								dirArrowStyle: true
							},
							getPathStyle: function(pathItem, zoom) {
								var color = '#2952C9';

								return {
									pathLineStyle: {
										strokeStyle: color,
										lineWidth: 6
									}
								}
							},
							renderAllPointsIfNumberBelow: 10000000 //绘制路线节点，如不需要可设置为-1
						}
					});

					_this.pathSimplifierIns = pathSimplifierIns;

					//设置数据

					let path = data[0].points.map(item => [item.longitude, item.latitude]);

					_this.pathSimplifierIns.setData([{
						name: '路线0',
						path
					}]);

					//对第一条线路（即索引 0）创建一个巡航器
					var navg1 = _this.pathSimplifierIns.createPathNavigator(0, {
						loop: false, //循环播放
						speed: 100, //巡航速度，单位千米/小时
						pathNavigatorStyle: {
							width: 24,
							height: 24,
							//使用图片
							content: PathSimplifier.Render.Canvas.getImageContent('static/icon/iv_xunjianperson.png', onload, onerror),
							strokeStyle: null,
							fillStyle: null,
							//经过路径的样式
							pathLinePassedStyle: {
								lineWidth: 6,
								strokeStyle: 'red',
								dirArrowStyle: {
									stepSpace: 15,
									strokeStyle: '#fff'
								}
							}
						}
					});

					navg1.start();
				})
			},
			setMap(newValue) {
				if (newValue.longitude) {
					let pos = new AMap.LngLat(newValue.longitude, newValue.latitude);
				
					this.map.setCenter(pos);
				}
				
				if (newValue.polygons.length > 0) {
					newValue.polygons.forEach(item => {
						let path = item.points.map(point => new AMap.LngLat(point.longitude, point.latitude));
				
						let polygon = new AMap.Polygon({
							path,
							strokeColor: "#ff0000",
							strokeWeight: 6,
							strokeOpacity: 0.5,
							fillOpacity: 0,
							strokeStyle: 'dashed',
							zIndex: 50,
						});
				
						this.map.add(polygon);
					})
				}
				
				if (newValue.polyline.length > 0) {
					setTimeout(()=> {
						this.updateCruise(newValue.polyline);
					}, 1000);
				}
			},
			updateMap(newValue, oldValue, ownerInstance, instance) {
				let timer = null;
				
				let cycle = () => {
					if(timer) clearTimeout(timer);
					
					if(typeof window.AMap === 'object'){
						this.setMap(newValue);
					} else {
						timer = setTimeout(cycle, 1000);
					}
				}
				
				cycle();
			},
			initAmap() {
				this.map = new AMap.Map('amap', {
					resizeEnable: true,
					zooms: [4, 20], //设置地图级别范围
					zoom: 11
				})

				this.map.on('complete', () => {})

				const srciptUI = document.createElement('script');
				srciptUI.src = 'https://webapi.amap.com/ui/1.1/main.js?v=1.1.1';

				document.head.appendChild(srciptUI);
			},
			initAmapUI() {},
			initMap() {
				if (typeof window.AMap === 'object') {
					this.initAMap();
				} else {
					const script = document.createElement('script');
					script.src = 'https://webapi.amap.com/maps?v=2.0&key=' + '890651203817fd12f51fcdb0c4ef6072';

					script.onload = this.initAmap.bind(this);

					document.head.appendChild(script);
				}
			}
		},

		created() {
			this.initMap();
		},
		mounted() {
			
		}
	}
</script>
<script>
	import { getUserTrajectory, getRegions, queryClockList} from '@/api/configure.js';
	import { deepClone, mergeUrls, getLocation, getSystemInfo, reverseGeocode, getUserInfo,timesFormat} from '@/util/util.js';
	import configUrl from '@/util/url.js';

	export default {
		data() {
			return {
				searchData: [{
					type: 'cal',
					label: '查询日期',
					field: 'date',
					value: '',
				}, {
					type: 'select',
					field: 'userId',
					label: '人员列表',
					index: 0,
					value: '',
					options: []
				}],
				option: {
					polygons: [],
					polyline: [],
					latitude: '', //维度 y
					longitude: '' //经度 x
				},
				polygons: [],
				polyline: [],
				userId: '',
				roleKey: '',
				latitude: '', //维度 y
				longitude: '', //经度 x
				mapHeight: '',
				mapWidth: ''
			}
		},
		methods: {
			async getRegions() {
				let coordinates = [];
				let params = {
					admincode: '610190'
				}

				let {
					code,
					data
				} = await getRegions(params);

				if (code == 0) {
					coordinates = JSON.parse(data.bdboundary)['coordinates'];
				}

				return coordinates;
			},
			async loadMap() {
				let systemInfo = await getSystemInfo();
				this.mapWidth = systemInfo.windowWidth;
				this.mapHeight = systemInfo.windowHeight - 49;

				let polygon = [];

				let getCoordinates = (data) => {
					let isMulti = data.find(item => item.find(it => typeof it == 'number'));

					if (isMulti) {
						let points = data.map(item => ({
							latitude: item[1],
							longitude: item[0]
						}))

						let obj = {points}

						polygon.push(obj)
					} else {
						data.forEach(item => {
							getCoordinates(item);
						});
					}
				}

				let coordinates = await this.getRegions();

				getCoordinates(coordinates);

				this.polygons = [...polygon];
			},
			async queryClockList() {
				let params = {
					type:1
				};
				
				this.searchData.forEach( item => {
					if(item.field == 'date'){
						params[item.field] = item.value;
					}
				});
				
				let {code, rows} = await queryClockList(params);
				
				let list = [];
				
				if(code == 0){
					list = rows.slice(0);
				}
				
				return list;
			},
			async getLocation() {
				let res = await getLocation();

				if (res.latitude && res.longitude) {
					this.longitude = res.longitude;
					this.latitude = res.latitude;
					this.address = res.address ? `${res.address.city}${res.address.district}${res.address.street}${res.address.streetNum}` : '地址';
				}
			},
			async getUserTrajectory() {
				let params = {
					userId: this.userId,
				}

				let otherParams = {};

				this.searchData.forEach(item => otherParams[item.field] = item.value);

				Object.assign(params, otherParams);

				let coordinates = [];

				let {
					code,
					data
				} = await getUserTrajectory(params);

				if (code == 0 && data) {
					coordinates = JSON.parse(data)['coordinates'];
				}

				return coordinates;
			},
			async setMapPos() {
				let coordinates = await this.getUserTrajectory();

				let points = coordinates.map(coordinate => ({
					latitude: coordinate[1],
					longitude: coordinate[0]
				}));

				let polyline = {
					color: '#d81e06',
					width: 6,
					borderWidth: 2,
					points: points,
					arrowLine: true
				};

				this.polyline = [];
				
				this.polyline = [polyline];
				
				this.option.longitude = this.longitude;
				this.option.latitude = this.latitude;
				this.option.polygons = this.polygons;
				this.option.polyline = this.polyline;
			},
			async setVal() {
				this.searchData.forEach((item) => {
					if (item.field == 'date') {
						item.value =  timesFormat(new Date().getTime(), 'yyyy-MM-dd');
					}
				})
				
				if(this.roleKey == 'dcy') {
					let clocks = await this.queryClockList();
					let users = this.searchData.find( item => item.field == 'userId');
					
					if(users) {
						users.options = clocks.map( clock => ({name: clock.user_name, code: clock.user_id}));
						users.value = users.options[0]['code'];	
						users.index = 0;
					}
				} else {
					this.searchData.splice(1, 1);
				}
				
				
			},
			async bindDateChange(e, item) {
				let date = e.detail.value;
				
				item.value = date;
				
				if(this.roleKey == 'dcy'){
					let clocks = await this.queryClockList();
					
					let users = this.searchData.find( item => item.field == 'userId');
					
					users.options = clocks.map( clock => ({name: clock.user_name, code: clock.user_id}));
					
					users.value = users.options[0]['code'];	
					users.index = 0;
				}
				
				
				await this.setMapPos();
			},
			
			async bindPickerChange(e, item){
				item.index = e.detail.value;
				item.value = item.options[item.index]['code'];
					
				await this.setMapPos();
			},
			
			async init() {
				let userInfo = getUserInfo();
				
				if (userInfo) {
					this.userId = userInfo['userId'];
					this.roleKey = userInfo['roles'][0]['roleKey'];
				}

				this.setVal();
				
				await this.loadMap();
				await this.getLocation();
				await this.setMapPos();
			}
		},
		onLoad() {
			this.init();
		},
		onReady() {
			
		}
	}
</script>
<style>
	.form {
		position: absolute;
		top: 0px;
		right: 0px;
		left: 0px;
		z-index: 2;
		background-color: #ffffff;
	}
	
	.form-group {
		padding: 7px 0px;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	
	.form-item {
		margin-bottom: 6px;
		display: flex;
		flex-direction: row;
		width: 186px;
	}
	
	.form-item-header{
		padding: 7px 6px 7px 6px;
		font-size: 12px;
		line-height: 15px;
		color: #5d5d5d;
	}
	
	.form-item-body{
		padding: 0px 7px 0px 0px;
		flex: 1;
	}
	
	.cals {
		padding: 6px 6px;
		border: 1px solid #c4c4c4;
		border-radius: 5px;
		position: relative;
		top: 0px;
		left: 0px;
	}
	
	.form-control-static{
		padding: 7px 6px 7px 0px;
		font-size: 12px;
		line-height: 15px;
		color: #5d5d5d;
	}
	
	.cals-item-content {
		font-size: 12px;
		line-height: 15px;
		color: #5d5d5d;
		position: relative;
		top: 0px;
		left: 0px;
	}
	
	.cals-icon {
		position: absolute;
		right: 3px;
		top: 3px;
		width: 20px;
		height: 20px;
	}
	
	.select{
		border: 1px solid #c4c4c4;
		border-radius: 5px;
		position: relative;
		top: 0px;
		left: 0px;
	}
	
	.selected{
		padding: 5px 25px 5px 8px;
		font-size: 12px;
		line-height: 16px;
		color: #5d5d5d;
	}
	
	.selected-con{
		font-size: 12px;
		line-height: 16px;
		color: #5d5d5d;
	}
	
	.select-icon{
		width: 26px;
		height: 26px;
		position: absolute;
		top: 0px;
		right: 0px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.map-wrap {
		margin-top: 49px;
		position: absolute;
		top: 0px;
		right: 0px;
		bottom: 0px;
		left: 0px;
	}
</style>
